// 导入库模块
use moyan::args::{ArgParser, show_help, show_version};
use moyan::config::{CliArgs, ExecutionMode, OperationMode, OutputFormat};
use moyan::errors::{CompilerError, ErrorKind};
use moyan::interpreter::Interpreter;
use moyan::lexer::Lexer;
use moyan::parser::Parser;

// 包含构建信息
include!(concat!(env!("OUT_DIR"), "/build_info.rs"));

use std::env;
use std::fs;
use std::io::{self, Write};
use std::process;
use std::time::Instant;

#[cfg(windows)]
use winapi::um::wincon::SetConsoleOutputCP;

fn main() {
    // 设置Windows控制台UTF-8编码
    #[cfg(windows)]
    {
        unsafe {
            SetConsoleOutputCP(65001);
        }
    }

    let args: Vec<String> = env::args().collect();

    // 解析命令行参数
    let mut parser = ArgParser::new(args);
    let cli_args = match parser.parse() {
        Ok(args) => args,
        Err(e) => {
            eprintln!("参数错误: {:?}", e);
            eprintln!("使用 'moyan help' 查看帮助信息");
            process::exit(1);
        }
    };

    // 根据模式执行相应操作
    match cli_args.mode {
        OperationMode::Help => {
            show_help();
            return;
        }
        OperationMode::Version => {
            show_version();
            return;
        }
        OperationMode::Repl => {
            run_repl(&cli_args);
        }
        OperationMode::Run => {
            if let Some(filename) = &cli_args.input_file {
                run_file(filename, &cli_args);
            } else {
                eprintln!("错误: 运行模式需要指定文件");
                eprintln!("使用 'moyan help' 查看帮助信息");
                process::exit(1);
            }
        }
        OperationMode::Check => {
            if let Some(filename) = &cli_args.input_file {
                check_file(filename, &cli_args);
            } else {
                eprintln!("错误: 检查模式需要指定文件");
                process::exit(1);
            }
        }
        OperationMode::Format => {
            if let Some(filename) = &cli_args.input_file {
                format_file(filename, &cli_args);
            } else {
                eprintln!("错误: 格式化模式需要指定文件");
                process::exit(1);
            }
        }
    }
}

fn run_file(filename: &str, cli_args: &CliArgs) {
    if cli_args.config.execution_mode != ExecutionMode::Quiet {
        println!("正在执行: {}", filename);
    }

    let start_time = Instant::now();

    match fs::read_to_string(filename) {
        Ok(source) => {
            if let Err(e) = execute_with_config(&source, cli_args, Some(filename)) {
                eprintln!("执行错误: {}", e);

                if cli_args.config.show_statistics {
                    let duration = start_time.elapsed();
                    eprintln!("执行时间: {:?}", duration);
                }

                process::exit(1);
            }

            if cli_args.config.show_statistics {
                let duration = start_time.elapsed();
                println!("执行成功，耗时: {:?}", duration);
            }
        }
        Err(e) => {
            eprintln!("无法读取文件 {}: {}", filename, e);
            process::exit(1);
        }
    }
}

fn check_file(filename: &str, cli_args: &CliArgs) {
    if cli_args.config.execution_mode != ExecutionMode::Quiet {
        println!("正在检查: {}", filename);
    }

    let start_time = Instant::now();

    match fs::read_to_string(filename) {
        Ok(source) => {
            // 词法分析
            let mut lexer = Lexer::new_with_config(&source, cli_args.config.clone());
            match lexer.tokenize() {
                Ok(tokens) => {
                    // 语法分析
                    let mut parser = Parser::new(tokens, filename.to_string(), source.clone());
                    match parser.parse() {
                        Ok(_) => {
                            if cli_args.config.execution_mode != ExecutionMode::Quiet {
                                println!("✅ 文件语法正确");
                            }

                            if cli_args.config.show_statistics {
                                let duration = start_time.elapsed();
                                println!("检查完成，耗时: {:?}", duration);
                            }
                        }
                        Err(e) => {
                            // 简化错误信息显示
                            match e.kind {
                                ErrorKind::SyntaxError => {
                                    eprintln!("❌ 语法错误: {}", e.message);
                                    if let Some(ref suggestion) = e.suggestion {
                                        eprintln!("💡 建议: {}", suggestion);
                                    }
                                }
                                ErrorKind::LexicalError => {
                                    eprintln!("❌ 词法错误: {}", e.message);
                                    if let Some(ref suggestion) = e.suggestion {
                                        eprintln!("💡 建议: {}", suggestion);
                                    }
                                }
                                ErrorKind::RuntimeError => {
                                    eprintln!("❌ 运行错误: {}", e.message);
                                    if let Some(ref suggestion) = e.suggestion {
                                        eprintln!("💡 建议: {}", suggestion);
                                    }
                                }
                                _ => {
                                    eprintln!("❌ 错误: {}", e.message);
                                    if let Some(ref suggestion) = e.suggestion {
                                        eprintln!("💡 建议: {}", suggestion);
                                    }
                                }
                            }
                            process::exit(1);
                        }
                    }
                }
                Err(e) => {
                    // 简化错误信息显示
                    eprintln!("❌ 错误: {}", e);
                    process::exit(1);
                }
            }
        }
        Err(e) => {
            eprintln!("无法读取文件 {}: {}", filename, e);
            process::exit(1);
        }
    }
}

fn format_file(filename: &str, cli_args: &CliArgs) {
    if cli_args.config.execution_mode != ExecutionMode::Quiet {
        println!("正在格式化: {}", filename);
    }

    match fs::read_to_string(filename) {
        Ok(source) => {
            // 这里可以实现格式化逻辑
            // 目前只是简单地输出原始内容
            if cli_args.config.execution_mode != ExecutionMode::Quiet {
                println!("格式化功能开发中...");
                println!("原始内容:");
                println!("{}", source);
            }
        }
        Err(e) => {
            eprintln!("无法读取文件 {}: {}", filename, e);
            process::exit(1);
        }
    }
}

fn run_repl(cli_args: &CliArgs) {
    match cli_args.config.output_format {
        OutputFormat::Json => {
            println!("{{\"version\":\"0.1.0\",\"mode\":\"repl\",\"status\":\"started\"}}");
        }
        OutputFormat::Colored | OutputFormat::Plain => {
            println!("墨言·文心 交互式解释器 v0.1.0");

            if cli_args.config.execution_mode.is_debug() {
                println!("模式: {:?}", cli_args.config.execution_mode);
                println!("输出格式: {:?}", cli_args.config.output_format);
                if let Some(timeout) = cli_args.config.resource_limits.max_execution_time {
                    println!("执行超时: {:?}", timeout);
                }
            }

            println!("输入 /quit 退出");
            println!();
        }
    }

    let mut interpreter = Interpreter::with_config(cli_args.config.clone());

    // 设置REPL配置
    if cli_args.config.enable_safety_checks {
        interpreter.enable_safety_checks();
    }

    loop {
        match cli_args.config.output_format {
            OutputFormat::Json => {
                print!("{{\"prompt\":\"墨言> \"}}");
            }
            _ => {
                print!("墨言> ");
            }
        }

        io::stdout().flush().unwrap();

        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();

        let input = input.trim();

        if input == "/quit" {
            match cli_args.config.output_format {
                OutputFormat::Json => {
                    println!("{{\"status\":\"exiting\"}}");
                }
                _ => {
                    println!("再见！");
                }
            }
            break;
        }

        if input.is_empty() {
            continue;
        }

        // 特殊REPL命令
        if input.starts_with("/") {
            handle_repl_command(input, cli_args, &mut interpreter);
            continue;
        }

        // REPL模式：包装成简单程序
        let wrapped = format!("篇章 交互\n引言\n毕\n正文\n{}\n毕\n结语\n毕", input);

        let start_time = Instant::now();
        match execute_with_config_and_interpreter(&wrapped, cli_args, &mut interpreter) {
            Ok(_) => {
                if cli_args.config.show_statistics {
                    let duration = start_time.elapsed();
                    match cli_args.config.output_format {
                        OutputFormat::Json => {
                            println!("{{\"execution_time\":\"{:?}\"}}", duration);
                        }
                        _ => {
                            println!("(执行时间: {:?})", duration);
                        }
                    }
                }
            }
            Err(e) => match cli_args.config.output_format {
                OutputFormat::Json => {
                    eprintln!("{{\"error\":\"{:?}\"}}", e);
                }
                _ => {
                    // 在REPL模式下提供更友好的错误信息
                    if let Some(compiler_err) = e.downcast_ref::<CompilerError>() {
                        match compiler_err.kind {
                            ErrorKind::SyntaxError => {
                                eprintln!("❌ 语法错误: {}", compiler_err.message);
                                if let Some(ref suggestion) = compiler_err.suggestion {
                                    eprintln!("💡 建议: {}", suggestion);
                                }
                            }
                            ErrorKind::LexicalError => {
                                eprintln!("❌ 词法错误: {}", compiler_err.message);
                                if let Some(ref suggestion) = compiler_err.suggestion {
                                    eprintln!("💡 建议: {}", suggestion);
                                }
                            }
                            ErrorKind::RuntimeError => {
                                eprintln!("❌ 运行错误: {}", compiler_err.message);
                                if let Some(ref suggestion) = compiler_err.suggestion {
                                    eprintln!("💡 建议: {}", suggestion);
                                }
                            }
                            ErrorKind::TypeMismatch => {
                                eprintln!("❌ 类型错误: {}", compiler_err.message);
                                if let Some(ref suggestion) = compiler_err.suggestion {
                                    eprintln!("💡 建议: {}", suggestion);
                                }
                            }
                            ErrorKind::UndefinedIdentifier => {
                                eprintln!("❌ 名称错误: {}", compiler_err.message);
                                if let Some(ref suggestion) = compiler_err.suggestion {
                                    eprintln!("💡 建议: {}", suggestion);
                                }
                            }
                            _ => {
                                eprintln!("❌ 错误: {}", compiler_err.message);
                                if let Some(ref suggestion) = compiler_err.suggestion {
                                    eprintln!("💡 建议: {}", suggestion);
                                }
                            }
                        }
                    } else {
                        // 非CompilerError类型的错误
                        eprintln!("❌ 错误: {}", e);
                    }
                }
            },
        }
    }
}

fn handle_repl_command(command: &str, cli_args: &CliArgs, interpreter: &mut Interpreter) {
    match command {
        "/help" => {
            println!("REPL命令:");
            println!("  /help     - 显示帮助");
            println!("  /quit     - 退出REPL");
            println!("  /clear    - 清屏");
            println!("  /reset    - 重置解释器状态");
            println!("  /vars     - 显示变量");
            println!("  /config   - 显示当前配置");
        }
        "/clear" => {
            print!("\x1B[2J\x1B[1;1H");
        }
        "/reset" => {
            *interpreter = Interpreter::with_config(cli_args.config.clone());
            println!("解释器已重置");
        }
        "/vars" => {
            // 这里可以添加显示变量的逻辑
            println!("变量显示功能开发中...");
        }
        "/config" => match cli_args.config.output_format {
            OutputFormat::Json => {
                println!(
                    "{{\"execution_mode\":\"{:?}\",\"output_format\":\"{:?}\",\"optimizations\":{},\"safety_checks\":{}}}",
                    cli_args.config.execution_mode,
                    cli_args.config.output_format,
                    cli_args.config.enable_optimizations,
                    cli_args.config.enable_safety_checks
                );
            }
            _ => {
                println!("当前配置:");
                println!("  执行模式: {:?}", cli_args.config.execution_mode);
                println!("  输出格式: {:?}", cli_args.config.output_format);
                println!("  优化: {}", cli_args.config.enable_optimizations);
                println!("  安全检查: {}", cli_args.config.enable_safety_checks);
                println!("  模块缓存: {}", cli_args.config.enable_module_cache);
                println!("  显示统计: {}", cli_args.config.show_statistics);
            }
        },
        _ => {
            eprintln!("未知命令: {}", command);
            eprintln!("使用 /help 查看可用命令");
        }
    }
}

fn execute_with_config(
    source: &str,
    cli_args: &CliArgs,
    file_path: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut interpreter = Interpreter::with_config(cli_args.config.clone());

    // 设置当前文件路径，用于模块导入时的相对路径解析
    if let Some(path) = file_path {
        interpreter.set_current_file_path(std::path::PathBuf::from(path));
    }

    execute_with_config_and_interpreter(source, cli_args, &mut interpreter)
}

fn execute_with_config_and_interpreter(
    source: &str,
    cli_args: &CliArgs,
    interpreter: &mut Interpreter,
) -> Result<(), Box<dyn std::error::Error>> {
    // 应用配置
    if !cli_args.config.enable_optimizations {
        // 禁用优化的逻辑
    }

    if cli_args.config.enable_safety_checks {
        interpreter.enable_safety_checks();
    }

    // 词法分析
    let mut lexer = Lexer::new_with_config(source, cli_args.config.clone());
    let tokens = lexer.tokenize()?;

    if cli_args.config.execution_mode.is_debug() {
        println!("词法分析完成，共 {} 个token", tokens.len());
    }

    // 语法分析
    let mut parser = Parser::new_with_config(
        tokens,
        "<input>".to_string(),
        source.to_string(),
        cli_args.config.clone(),
    );
    let ast = parser.parse()?;

    if cli_args.config.execution_mode.is_debug() {
        println!("语法分析完成");
    }

    // 解释执行
    interpreter.eval(&ast)?;

    Ok(())
}
